package com.cash.app.base

import android.app.Activity
import android.content.Intent
import com.cash.app.manager.LoginManager.isLogin
import com.cash.app.ui.login.LoginActivity
import com.cash.app.utils.TLog

object JumpInterceptor {

    const val TAG = "JumpInterceptor"

    private var pendingAction: (() -> Unit)? = null

    const val LOGIN_REQUEST_CODE = 10001
    const val AUTH_REQUEST_CODE = 10002


    fun intercept(
        activity: Activity, action: () -> Unit, needLogin: Boolean = true
    ) {
        if (!isLogin() && needLogin) { // Start login activity
            TLog.d("intercept to login", TAG)
            pendingAction = action
            val intent = Intent(activity, LoginActivity::class.java)
            activity.startActivityForResult(intent, LOGIN_REQUEST_CODE)
            return
        }

//        if (!isAuthCompleted() && needAuth) { // Start auth activity
//            TLog.d("intercept to auth", TAG)
//            pendingAction = action
//            val intent = Intent(activity, AuthActivity::class.java)
//            activity.startActivityForResult(intent, AUTH_REQUEST_CODE)
//            return
//        }
        TLog.d("not intercept", TAG)
        action.invoke()
    }

    fun handleResult(activity: Activity, requestCode: Int, resultCode: Int) {
        TLog.d("handleResult requestCode=$requestCode resultCode=$resultCode", TAG)
        when (requestCode) {
            LOGIN_REQUEST_CODE -> {
                when (resultCode) {
                    Activity.RESULT_OK -> {
                        if (pendingAction != null) {
                            TLog.d("handleResult login success, jump to pendingAction", TAG)
                            pendingAction?.invoke()
                            pendingAction = null
                        }
                    }

                    else -> {
                        TLog.d("handleResult login quit", TAG)
                        pendingAction = null
                    }
                }
            }

            AUTH_REQUEST_CODE -> {
                when (resultCode) {
                    Activity.RESULT_OK -> {
                        TLog.d("handleResult auth success, jump to pendingAction", TAG)
                        pendingAction?.invoke()
                        pendingAction = null
                    }

                    else -> {
                        TLog.d("handleResult auth quit", TAG)
                        pendingAction = null
                    }
                }
            }
        }
    }
}
